package com.fbt.transfer.app.driver.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import cn.hutool.core.collection.CollUtil;
import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.baidu.BaiDuLocationUtil;
import com.fbt.transfer.app.driver.databinding.ActivityMainBinding;
import com.fbt.transfer.app.driver.http.AbstractCallback;
import com.fbt.transfer.app.driver.socket.SocketManager;
import com.fbt.transfer.app.driver.ui.index.IndexViewModel;
import com.fbt.transfer.app.driver.util.LogUtils;
import com.fbt.transfer.app.driver.util.PermissionUtils;
import com.fbt.transfer.app.driver.util.UserManager;
import com.permissionx.guolindev.PermissionX;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class MainActivity extends BaseActivity {

  private ActivityMainBinding activityMainBinding = null;
  private static final String TAG = "MainActivity";
  private IndexViewModel indexViewModel = null;


  @Override
  protected void initView () {
    activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(activityMainBinding.getRoot());

    // 初始化ViewModel
    indexViewModel = new ViewModelProvider(this).get(IndexViewModel.class);
    // 初始化自定义toolbar
    initCustomToolbar();
  }


  /**
   * 初始化自定义toolbar
   */
  private void initCustomToolbar () {
    View toolbarView = findViewById(R.id.custom_toolbar);

    // 获取Socket状态指示器和文本
    View socketStatusIndicator = toolbarView.findViewById(R.id.socket_status_indicator);
    TextView socketStatusText = toolbarView.findViewById(R.id.socket_status_text);

    // 获取消息图标和消息数量文本
    View messageIconContainer = toolbarView.findViewById(R.id.message_icon_container);
    TextView messageCountText = toolbarView.findViewById(R.id.message_count);

    // 监听Socket连接状态变化
    SocketManager socketManager = SocketManager.getInstance(this);
    socketManager.setConnectionStateListener(isConnected -> {
      // 更新Socket状态指示器为开关式滑块
      if (socketStatusIndicator instanceof androidx.appcompat.widget.SwitchCompat) {
        androidx.appcompat.widget.SwitchCompat socketSwitch =
            (androidx.appcompat.widget.SwitchCompat) socketStatusIndicator;
        socketSwitch.setChecked(isConnected);
      }
      // 更新状态文本
      socketStatusText.setText(isConnected ? "在线" : "离线");
    });
    socketManager.connect();
    // 观察统计数据变化并更新未读消息数量
    indexViewModel.getIndexStatsLiveData().observe(this, indexStats -> {
      if (indexStats != null && indexStats.getMessageCount() != null && indexStats.getMessageCount() > 0) {
        messageCountText.setVisibility(View.VISIBLE);
        messageCountText.setText(String.valueOf(indexStats.getMessageCount()));
      } else {
        messageCountText.setVisibility(View.GONE);
      }
    });

    // 添加消息图标点击事件
    messageIconContainer.setOnClickListener(v -> {
      // 这里可以跳转到消息列表页面
      // 示例：跳转到消息页面的代码
      // Intent intent = new Intent(MainActivity.this, MessageActivity.class);
      // startActivity(intent);

      // 临时使用Toast提示功能正在开发中
      Toast.makeText(MainActivity.this, "消息功能正在开发中", Toast.LENGTH_SHORT).show();
    });
  }

  @Override
  protected void onPostCreate (Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // 隐藏默认ActionBar，因为我们使用自定义toolbar
    if (getSupportActionBar() != null) {
      getSupportActionBar().hide();
    }

    // 在Activity完全创建后设置导航控制器，避免Fragment加载问题
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
        R.id.navigation_index, R.id.navigation_grab, R.id.navigation_me)
        .build();
    // 确保Fragment容器已经准备好
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
    // 不再设置ActionBar，因为我们使用自定义toolbar
    // NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

    // 添加导航监听器，用于控制统计视图的可见性
    navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
      // 获取统计视图
      View indexStatsView = findViewById(R.id.index_stats_view);
      // 根据目的地ID控制统计视图的可见性
      // 统计视图已迁移到Fragment，无需控制可见性
    });

    // 使用NavigationUI自动处理底部导航与NavController的关联
    NavigationUI.setupWithNavController(activityMainBinding.navView, navController);

    // 默认选中首页，确保统计视图初始状态正确
    if (activityMainBinding.navView.getSelectedItemId() != R.id.navigation_index) {
     // findViewById(R.id.index_stats_view).setVisibility(View.GONE);
      Optional.ofNullable(findViewById(R.id.index_stats_view)).ifPresent(x->findViewById(R.id.index_stats_view).setVisibility(View.GONE));
    }
  }

  @Override
  protected void initListener () {
    checkPermission();
  }

  private boolean isOPenGPS (final Context context) {
    LocationManager locationManager =
        (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    // GPS定位
    boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    // 网络服务定位
    boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (gps || network) {
      return true;
    }
    return false;
  }

  /**
   * 检查权限：ACCESS_FINE_LOCATION，ACCESS_COARSE_LOCATION，ACCESS_NETWORK_STATE，ACCESS_WIFI_STATE
   */
  private void checkPermission () {
    if (!isOPenGPS(MainActivity.this)) {
      Toast.makeText(MainActivity.this, "未开启定位，无法获取地理位置", Toast.LENGTH_SHORT).show();
    }
    // 调用拔打电话，先检查有没有拔打电话的权限，没有就申请
    List<String> permissions = new ArrayList<>();
    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
      permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    startServiceMinimap();
    if (!permissions.isEmpty()) {
      // 申请权限
      PermissionX.init(MainActivity.this)
          .permissions(permissions)
          .explainReasonBeforeRequest()
          .onExplainRequestReason(
              (scope, deniedList) ->
                  scope.showRequestReasonDialog(deniedList, "运行APP依赖位置信息权限", "我已明白", "拒绝"))
          .request(
              (allGranted, grantedList, deniedList) -> {
                if (CollUtil.isNotEmpty(deniedList)) {
                  Toast.makeText(MainActivity.this, "部分权限被拒绝", Toast.LENGTH_SHORT).show();
                } else {
                  BaiDuLocationUtil.getInstance().startLocation(false);
                }
              });
    } else {
      BaiDuLocationUtil.getInstance().startLocation(false);
    }
  }

  public void startServiceMinimap() {
    // 判断是否有悬浮窗权限
    if (PermissionUtils.hasOverlayPermission(MainActivity.this)) {
      Log.d(TAG, "悬浮窗权限已授予");
      // 权限已授予，可以启动悬浮窗服务
    } else {
      // 检查是否已经请求过悬浮窗权限
      if (!PermissionUtils.hasRequestedOverlayPermission(MainActivity.this)) {
        Log.d(TAG, "悬浮窗权限未授予，准备跳转设置");
        // 标记已请求过悬浮窗权限
        PermissionUtils.markOverlayPermissionRequested(MainActivity.this);
        jumpToPermission();
      } else {
        // 已经请求过权限，但用户拒绝了，不再重复请求
        Log.d(TAG, "悬浮窗权限已请求过但未授予，不再重复请求");
      }
    }
  }

  // 跳转系统设置-悬浮窗页面
  public void jumpToPermission() {
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getApplicationContext().getPackageName()));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getApplicationContext().startActivity(intent);
  }
  
  @Override
  protected void initData () {
    //UserManager.getInstance(this).clearUserInfo();
    // 检查用户是否已登录
    if (!UserManager.getInstance(this).isLoggedIn()) {
      // 未登录，跳转到登录界面
      LogUtils.w("用户未登陆，准备跳转到登陆界面");
      Intent intent = new Intent(this, LoginActivity.class);
      startActivity(intent);
      finish();
      return;
    }
    apiInterface.checkLogin().enqueue(new AbstractCallback<Boolean>(MainActivity.this, false) {
      @Override
      protected void onSuccess (Boolean data) {
        if (Boolean.FALSE.equals(data)) {
          LogUtils.w("用户未登陆，准备跳转到登陆界面");
          Intent intent = new Intent(MainActivity.this, LoginActivity.class);
          startActivity(intent);
          finish();
        }
      }
    });
  }
}
